﻿<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>新增入库订单</title>
    <script src="https://unpkg.com/vue@3/dist/vue.global.js"></script>
    <script src="https://unpkg.com/element-plus/dist/index.full.js"></script>
    <link rel="stylesheet" href="https://unpkg.com/element-plus/dist/index.css">
    <script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>
    <style>
        .container {
            width: 95%;
            margin: 20px auto;
        }

        .form-group {
            margin-bottom: 20px;
            border: 1px solid #ebeef5;
            border-radius: 4px;
            padding: 20px;
            box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
        }

        .form-item {
            margin-bottom: 16px;
        }

        .note-input {
            height: 100px;
        }

        .upload-area {
            margin-top: 20px;
        }

        .custom-unit-select {
            min-width: 120px;
        }

        .tip {
            margin-top: 8px;
            color: #606266;
            font-size: 12px;
        }

        .related-order-row {
            display: flex;
            align-items: center;
            gap: 16px;
        }

        .action-buttons {
            display: flex;
            justify-content: flex-end;
            gap: 12px;
            margin-top: 24px;
        }

        .table-col-right {
            text-align: right;
        }

        .input-suffix-dots {
            position: absolute;
            right: 14px;
            top: 50%;
            transform: translateY(-70%);
            font-size: 22px;
            cursor: pointer;
            user-select: none;
        }

        .related-order-input:read-only {
            cursor: pointer;
        }
    </style>
</head>
<body>
    <div class="container">
        <!-- 基础信息 -->
        <div class="form-group">
            <h3>基础信息</h3>
            <el-form label-width="100px">
                <el-row>
                    <el-col :span="12">
                        <el-form-item label="入库单号" required class="form-item">
                            <el-input placeholder="自动获取系统编号" v-model="formData.inbound_no" readonly style="width: 360px;"></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="入库类型" required class="form-item">
                            <el-select v-model="formData.inbound_type" placeholder="请选择" style="width: 360px;" v-on:change="handleInboundTypeChange">
                                <el-option v-for="item in warehousingOptions" :key="item.dictValue" :label="item.dictLabel" :value="item.dictValue"></el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col :span="12">
                        <el-form-item label="仓库名称" required class="form-item">
                            <el-select v-model="formData.warehouse_id" placeholder="请选择" style="width: 360px;" v-on:change="handleWarehouseChange">
                                <el-option v-for="item in WarehouseTableData" :key="item.warehouse_id" :label="item.warehouse_name" :value="item.warehouse_id"></el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="入库日期" required class="form-item">
                            <el-date-picker v-model="formData.inbound_date" type="date" placeholder="请选择" style="width: 360px;"></el-date-picker>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col :span="12">
                        <el-form-item label="关联单号" class="form-item">
                            <div class="related-order-row">
                                <el-input v-model="formData.related_order_no"
                                          placeholder="请输入或点击选择"
                                          style="width: 360px;"
                                          :readonly="isRelatePurchaseOrder"
                                          class="related-order-input"
                                          v-on:click="handleRelatedOrderInputClick">
                                    <template #suffix>
                                        <span class="input-suffix-dots"
                                              v-if="isRelatePurchaseOrder"
                                              v-on:click="handleRelatedOrderInputClick">...</span>
                                    </template>
                                </el-input>
                                <el-checkbox v-model="isRelatePurchaseOrder"
                                             label="关联进货单号"
                                             v-on:change="handleRelatePurchaseOrderChange"
                                             style="margin-left: 10px;"></el-checkbox>
                            </div>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="供应商" class="form-item">
                            <el-select v-model="formData.supplier_id"
                                       placeholder="请选择"
                                       style="width: 360px;"
                                       v-on:change="handleSupplierChange"
                                       :disabled="isRelatePurchaseOrder">
                                <el-option v-for="item in supplierOptions" :key="item.supplier_id" :label="item.supplier_name" :value="item.supplier_id"></el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col :span="12">
                        <el-form-item label="联系人" class="form-item">
                            <el-input v-model="formData.contact_person" placeholder="请输入" disabled readonly style="width: 360px;"></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="联系方式" class="form-item">
                            <el-input v-model="formData.contact_information" placeholder="请输入" disabled readonly style="width: 360px;"></el-input>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col :span="12">
                        <el-form-item label="经办人" class="form-item">
                            <el-select v-model="formData.handler" placeholder="请选择" style="width: 360px;">
                                <el-option label="张三" value="1"></el-option>
                                <el-option label="李四" value="2"></el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col :span="24">
                        <el-form-item label="备注" class="form-item">
                            <el-input v-model="formData.note" type="textarea" placeholder="请输入" class="note-input"></el-input>
                        </el-form-item>
                    </el-col>
                </el-row>
            </el-form>
        </div>

        <!-- 入库明细 -->
        <div class="form-group">
            <h3>入库明细</h3>
            <el-row>
                <el-col :span="12">
                    <el-button type="success"
                               v-on:click="openGoodsDialog"
                               :disabled="isRelatePurchaseOrder && !formData.related_order_no">
                        添加
                    </el-button>
                    <el-button v-on:click="removeGoodsRow">移除</el-button>
                </el-col>
            </el-row>
            <el-table :data="tableData"
                      ref="multipleTableRef"
                      v-on:selection-change="handleSelectionChange"
                      style="width: 100%; margin-top: 16px;">
                <!-- 非关联状态表格列 -->
                <template v-if="!isRelatePurchaseOrder">
                    <el-table-column type="selection" width="55"></el-table-column>
                    <el-table-column prop="product_name" label="货品名称" width="120" fixed="left"></el-table-column>
                    <el- prop="product_code" label="货品编号" width="120" fixed="left"></el- table-column>
                    <el-table-column prop="type_of_goods_name" label="货品类型" width="120"></el-table-column>
                    <el-table-column prop="specification_model" label="规格型号" width="80"></el-table-column>
                    <el-table-column prop="unit_name" label="单位" width="80"></el-table-column>
                    <el-table-column prop="current_inventory" label="当前库存" width="100" class="table-col-right"></el-table-column>
                    <el-table-column label="入库库位" width="100">
                        <template #default="scope">
                            <el-select v-model="scope.row.inbound_location" placeholder="请选择" style="width: 100%;">
                                <el-option label="库位1" value="location1"></el-option>
                                <el-option label="库位2" value="location2"></el-option>
                            </el-select>
                        </template>
                    </el-table-column>
                    <el-table-column label="*本次入库数量" width="120">
                        <template #default="scope">
                            <el-input 
                                v-model.number="scope.row.this_inbound_quantity" 
                                type="number" 
                                min="0" 
                                :max="scope.row.uninbound_quantity" 
                                placeholder="请输入" 
                                style="width: 100%;"
                                @@input="handleInboundQuantityInput(scope.row)"
                                v-on:change="handleInboundQuantityChange(scope.row)">
                            </el-input>
                        </template>
                    </el-table-column>
                    <el-table-column prop="purchase_unit_price" label="入库单价" width="100" class="table-col-right"></el-table-column>
                    <el-table-column label="入库金额" width="120" class="table-col-right">
                        <template #default="scope">{{ (scope.row.this_inbound_quantity * scope.row.purchase_unit_price || 0).toFixed(2) }}</template>
                    </el-table-column>
                    <el-table-column label="批次号" width="100">
                        <template #default="scope"><el-input v-model="scope.row.batch_no" placeholder="请输入" style="width: 100%;"></el-input></template>
                    </el-table-column>
                    <el-table-column label="生产日期" width="120">
                        <template #default="scope"><el-date-picker v-model="scope.row.production_date" type="date" placeholder="请选择" style="width: 100%;"></el-date-picker></template>
                    </el-table-column>
                    <el-table-column label="备注" width="120">
                        <template #default="scope"><el-input v-model="scope.row.note" placeholder="请输入" style="width: 100%;"></el-input></template>
                    </el-table-column>
                    <el-table-column fixed="right" label="操作" width="100">
                        <template #default="scope"><el-button link type="danger" size="small" v-on:click="handleDeleteRow(scope.row)">移除</el-button></template>
                    </el-table-column>
                </template>
                <!-- 关联状态表格列 -->
                <template v-else>
                    <el-table-column type="selection" width="55"></el-table-column>
                    <el-table-column prop="product_name" label="货品名称" width="120"></el-table-column>
                    <el-table-column prop="product_code" label="货品编号" width="120"></el-table-column>
                    <el-table-column prop="type_of_goods_name" label="货品类型" width="120"></el-table-column>
                    <el-table-column prop="specification_model" label="规格型号" width="80"></el-table-column>
                    <el-table-column prop="unit_name" label="单位" width="80"></el-table-column>
                    <el-table-column prop="current_inventory" label="当前库存" width="100" class="table-col-right"></el-table-column>
                    <el-table-column prop="prod_num" label="进货数量" width="100" class="table-col-right"></el-table-column>
                    <el-table-column prop="stkIn_num" label="已入库数量" width="100" class="table-col-right"></el-table-column>
                    <el-table-column prop="uninbound_quantity" label="未入库数量" width="100" class="table-col-right"></el-table-column>
                    <el-table-column label="*入库库位" width="120">
                        <template #default="scope">
                            <el-select v-model="scope.row.inbound_location" placeholder="请选择" style="width: 100%;">
                                <el-option v-for="item in warehouseList" :key="item.dictValue" :label="item.location_name" :value="item.location_id"></el-option>
                            </el-select>
                        </template>
                    </el-table-column>
                    <el-table-column label="*本次入库数量" width="120">
                        <template #default="scope">
                            <el-input 
                                v-model.number="scope.row.this_inbound_quantity" 
                                type="number" 
                                min="0" 
                                :max="scope.row.uninbound_quantity" 
                                placeholder="请输入" 
                                style="width: 100%;"
                                @@input="handleInboundQuantityInput(scope.row)"
                                v-on:change="handleInboundQuantityChange(scope.row)">
                            </el-input>
                        </template>
                    </el-table-column>
                    <el-table-column label="入库单价" width="120" class="table-col-right">
                        <template #default="scope">{{scope.row.purchase_unit_price}}</template>
                    </el-table-column>
                    <el-table-column label="入库金额" width="120" class="table-col-right">
                        <template #default="scope">{{ (scope.row.this_inbound_quantity * scope.row.purchase_unit_price || 0).toFixed(2) }}</template>
                    </el-table-column>
                    <el-table-column label="批次号" width="100">
                        <template #default="scope"><el-input v-model="scope.row.batch_no" placeholder="请输入" style="width: 100%;"></el-input></template>
                    </el-table-column>
                    <el-table-column label="生产日期" width="120">
                        <template #default="scope"><el-date-picker v-model="scope.row.production_date" type="date" placeholder="请选择" style="width: 100%;"></el-date-picker></template>
                    </el-table-column>
                    <el-table-column label="备注" width="120">
                        <template #default="scope"><el-input v-model="scope.row.note" placeholder="请输入" style="width: 100%;"></el-input></template>
                    </el-table-column>
                    <el-table-column fixed="right" label="操作" width="100">
                        <template #default="scope"><el-button link type="danger" size="small" v-on:click="handleDeleteRow(scope.row)">移除</el-button></template>
                    </el-table-column>
                </template>
            </el-table>
            <div style="text-align: right; color: #606266; margin-top: 8px;">
                货品种类：{{ tableData.length }} | 货品总数量：{{ calculateTotalNum }} | 总金额：{{ calculateTotalAmount }}
            </div>
        </div>

        <!-- 上传附件 -->
        <div class="form-group">
            <h3>上传附件</h3>
            <div class="upload-area">
                <el-upload action="/api/Upload"
                           :file-list="fileList"
                           v-on:success="handleUploadSuccess"
                           :before-upload="beforeUpload"
                           :limit="3">
                    <el-button type="primary" v-on:click="handleUploadClick">上传</el-button>
                </el-upload>
                <div class="tip">支持 doc、pdf、rar 等格式，单个文件最大 200MB。</div>
            </div>
        </div>

        <!-- 操作按钮 -->
        <div class="action-buttons">
            <el-button v-on:click="goBack">关闭</el-button>
            <el-button type="info" v-on:click="saveDraft">保存草稿</el-button>
            <el-button type="primary" v-on:click="saveAndAdd">保存并新增</el-button>
            <el-button type="success" v-on:click="save">保存</el-button>
        </div>
        
        <!-- 货品选择模态框 -->
        <el-dialog :title="isRelatePurchaseOrder ? '添加货品（关联订单：' + formData.related_order_no + '）' : '添加货品'"
                   v-model="dialogVisible"
                   width="800px">
            <el-form :inline="true" :model="goodsSearchForm" class="mb-4">
                <el-form-item label="货品编号/名称">
                    <el-input v-model="goodsSearchForm.goodsCodeName" placeholder="请输入"></el-input>
                </el-form-item>
                <el-form-item label="单位">
                    <el-select v-model="goodsSearchForm.unit" placeholder="请选择" class="custom-unit-select">
                        <el-option v-for="item in unitOptions" :key="item.dictValue" :label="item.dictLabel" :value="item.dictValue"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" v-on:click="queryGoods">查询</el-button>
                    <el-button v-on:click="resetGoodsForm">重置</el-button>
                </el-form-item>
            </el-form>
            <el-table :data="goodsTableData" border v-on:selection-change="val => selectedGoods = val">
                <el-table-column type="selection" width="55"></el-table-column>
                <el-table-column type="index" label="序号" width="60"></el-table-column>
                <el-table-column prop="product_code" label="货品编号" width="120"></el-table-column>
                <el-table-column prop="product_name" label="货品名称" width="120"></el-table-column>
                <el-table-column prop="specification_model" label="规格型号" width="100"></el-table-column>
                <el-table-column prop="unit_name" label="单位" width="80"></el-table-column>
                <el-table-column prop="purchase_unit_price" label="入库单价" width="100" class="table-col-right"></el-table-column>
                <el-table-column prop="current_inventory" label="当前库存" width="100" class="table-col-right"></el-table-column>
                <el-table-column prop="uninbound_quantity" label="未入库数量" width="120" class="table-col-right" v-if="isRelatePurchaseOrder"></el-table-column>
            </el-table>
            <el-pagination v-model:current-page="goodsCurrentPage"
                           v-model:page-size="goodsPageSize"
                           :page-sizes="[5, 10, 20, 50]"
                           :total="goodsTotal"
                           layout="total, sizes, prev, pager, next, jumper"
                           v-on:size-change="handleGoodsPageSizeChange"
                           v-on:current-change="handleGoodsCurrentPageChange"
                           style="margin-top: 16px; text-align: right;"></el-pagination>
            <template #footer>
                <div class="dialog-footer">
                    <el-button v-on:click="dialogVisible = false">取消</el-button>
                    <el-button type="primary" v-on:click="confirmSelectGoods">确定</el-button>
                </div>
            </template>
        </el-dialog>

        <!-- 选择进货单模态框 -->
        <el-dialog title="选择进货单" v-model="selectPurchaseOrderDialogVisible" width="1000px">
            <el-form :inline="true" :model="purchaseOrderSearchForm" class="mb-4">
                <el-form-item>
                    <el-input v-model="purchaseOrderSearchForm.purchaseOrderNo" style="width: 200px;" placeholder="进货单号"></el-input>
                </el-form-item>
                <el-form-item>
                    <el-select v-model="purchaseOrderSearchForm.status" style="width: 200px;" placeholder="单据状态">
                        <el-option label="未入库" value="5"></el-option>
                        <el-option label="部分入库" value="8"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item>
                    <el-select v-model="purchaseOrderSearchForm.supplier" placeholder="供应商" style="width: 200px;">
                        <el-option v-for="item in supplierOptions" :key="item.supplier_id" :label="item.supplier_name" :value="item.supplier_id"></el-option>
                    </el-select>
                </el-form-item>
                <br />
                <el-form-item>
                    <el-input v-model="purchaseOrderSearchForm.purchaser" style="width: 200px;" placeholder="进货人"></el-input>
                </el-form-item>
                <el-form-item>
                    <el-input v-model="purchaseOrderSearchForm.department" style="width: 200px;" placeholder="进货部门"></el-input>
                </el-form-item>
                <el-form-item>
                    <el-date-picker v-model="purchaseOrderSearchForm.date" style="width: 200px;" type="date" placeholder="日期"></el-date-picker>
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" v-on:click="queryPurchaseOrders">查询</el-button>
                    <el-button v-on:click="resetPurchaseOrderForm">重置</el-button>
                </el-form-item>
            </el-form>
            <el-table :data="purchaseOrderTableData" style="width: 100%" v-on:row-click="handlePurchaseOrderRowClick">
                <el-table-column type="radio" width="55"></el-table-column>
                <el-table-column type="index" label="序号" width="60"></el-table-column>
                <el-table-column prop="purchase_order_no" label="进货单号" width="120"></el-table-column>
                <el-table-column prop="document_status_label" label="单据状态" width="100"></el-table-column>
                <el-table-column prop="purchase_date" label="进货日期" width="120">
                    <template #default="scope">{{ new Date(scope.row.purchase_date).toLocaleDateString() }}</template>
                </el-table-column>
                <el-table-column prop="supplierName" label="供应商" width="120"></el-table-column>
                <el-table-column prop="organizations_name" label="进货部门" width="120"></el-table-column>
                <el-table-column prop="purchaser" label="进货人" width="120"></el-table-column>
                <el-table-column prop="totalQuantity" label="货品数量" width="100" class="table-col-right"></el-table-column>
                <el-table-column prop="totalAmount" label="进货金额" width="100" class="table-col-right">
            </el-table>
            <el-pagination v-model:current-page="purchaseOrderCurrentPage"
                           v-model:page-size="purchaseOrderPageSize"
                           :page-sizes="[5, 10, 20]"
                           :total="purchaseOrderTotal"
                           layout="total, sizes, prev, pager, next, jumper"
                           v-on:size-change="handlePurchaseOrderPageSizeChange"
                           v-on:current-change="handlePurchaseOrderCurrentPageChange"
                           style="margin-top: 16px; text-align: right;"></el-pagination>
            <template #footer>
                <div class="dialog-footer">
                    <el-button v-on:click="selectPurchaseOrderDialogVisible = false">取消</el-button>
                    <el-button type="primary" v-on:click="confirmSelectPurchaseOrder">确定</el-button>
                </div>
            </template>
    </div>

    <script>
        const { createApp, ref, reactive, computed, onMounted } = Vue;
        const app = createApp({
            setup() {
                // 基础表单数据
                const formData = reactive({
                    inbound_no: '',
                    inbound_type: '',
                    warehouse_id: '',
                    inbound_date: new Date(),
                    related_order_no: '',
                    supplier_id: '',
                    contact_person: '',
                    contact_information: '',
                    handler: '',
                    note: '',
                });

                // 关联进货单号勾选状态
                const isRelatePurchaseOrder = ref(false);
                // 上传文件列表
                const fileList = ref([]);
                // 入库明细表格数据
                const tableData = ref([]);
                // 入库类型字典
                const warehousingOptions = ref([]);
                // 仓库数据
                const WarehouseData = ref([]);
                // 供应商数据
                const supplierOptions = ref([]);
                // 表格选中项
                const selectedRows = ref([]);
                const multipleTableRef = ref(null);

                // 计算总数量和总金额
                const calculateTotalNum = computed(() =>
                    tableData.value.reduce((t, i) => t + Number(i.this_inbound_quantity || 0), 0)
                );
                const calculateTotalAmount = computed(() =>
                    tableData.value.reduce((t, i) => t + Number((i.this_inbound_quantity * (i.purchase_unit_price || 0)) || 0), 0).toFixed(2)
                );

                // 初始化数据
                onMounted(async () => {
                    await Promise.all([
                        getWarehousingTypeDict(),
                        loadWarehouseList(),
                        getSupplierList(),
                        generateLocationNumber()
                    ]);
                });
                

                // 生成库位编号 - 使用 rule_id=14（对应target_id=21）
                const generateLocationNumber = async () => {
                    try {
                        console.log("开始生成库位编号，使用rule_id=2");
                        const response = await axios.post(
                            '/NumberingRule/GenerateBusinessNumber',
                            { rule_id: 2 },  // 使用 rule_id=14，它对应 target_id=21
                            { headers: { 'Content-Type': 'application/json' } }
                        );
                        if (response.data.success) {
                            formData.inbound_no = response.data.businessNumber;
                            console.log("库位编号生成成功:", locationForm.locationNumber);
                        } else {
                            ElMessage.error(`库位编号生成失败：${response.data.message || '未知错误'}`);
                            locationForm.locationNumber = '';
                        }
                    } catch (error) {
                        console.error("生成库位编号异常:", error);
                        ElMessage.error('网络异常，无法生成库位编号，请重试');
                        locationForm.locationNumber = '';
                    }
                };

                // 获取入库类型字典
                const getWarehousingTypeDict = async () => {
                    try {
                        const res = await axios.get('/api/Dict/datas/WarehousingType');
                        warehousingOptions.value = res.data;
                    } catch (err) {
                        ElementPlus.ElMessage.error('获取入库类型失败');
                    }
                };
                const WarehouseTableData = ref([]);
                // 加载仓库列表
                const loadWarehouseList = async () => {
                    try {
                        const params = {
                            warehouseName:'',
                            warehouseStatus:'',
                            organizationId:'',
                            warehouseManager:'',
                            pageIndex: 1,
                            pageSize: 100
                        };
                        
                        const url = '@Url.Action("GetPageList", "Warehouse")';
                        const response = await fetch(`${url}?${new URLSearchParams(params)}`).then(res => res.json());

                        if (response && response.code === 200 && response.data) {
                            WarehouseTableData.value = response.data.data || [];
                            console.log(WarehouseTableData.value);
                        } else {
                            tableData.value = [];
                            pagination.totalCount = 0;
                            ElMessage.warning('未查询到仓库数据');
                        }
                    } catch (err) {
                        console.error("加载仓库列表失败：", err);
                        ElMessage.error(`加载失败：${err.message || '网络异常'}`);
                        tableData.value = [];
                        pagination.totalCount = 0;
                    }
                };

                // 获取供应商列表
                const getSupplierList = async () => {
                    try {
                        const res = await axios.get('/api/Supplier/GetList');
                        supplierOptions.value = res.data.data;
                    } catch (err) {
                        ElementPlus.ElMessage.error('获取供应商列表失败');
                    }
                };



                // 入库类型变更时清空关联数据
                const handleInboundTypeChange = () => {
                    if (isRelatePurchaseOrder.value) {
                        formData.related_order_no = '';
                        tableData.value = [];
                        storage();
                    }
                };

                // 仓库发生改变时
                const handleWarehouseChange = () => {
                    storage();
                };

                // 关联单号输入框点击
                const handleRelatedOrderInputClick = () => {
                    if (isRelatePurchaseOrder.value && formData.inbound_type) {
                        selectPurchaseOrderDialogVisible.value = true;
                        queryPurchaseOrders()
                    } else if (!formData.inbound_type) {
                        ElementPlus.ElMessage.warning('请先选择入库类型');
                    }
                };

                // 关联进货单勾选变更
                const handleRelatePurchaseOrderChange = (val) => {
                    if (!val) {
                        formData.related_order_no = '';
                        tableData.value = [];
                    }
                };

                // 进货单选择相关
                const selectPurchaseOrderDialogVisible = ref(false);
                const purchaseOrderSearchForm = reactive({
                    purchaseOrderNo: '',
                    status: '',
                    supplier: '',
                    purchaser: '',
                    department: '',
                    date: ''
                });
                const purchaseOrderTableData = ref([]);
                const purchaseOrderCurrentPage = ref(1);
                const purchaseOrderPageSize = ref(5);
                const purchaseOrderTotal = ref(0);

                // 点击进货单表格行
                const handlePurchaseOrderRowClick = (row) => {
                    purchaseOrderTableData.value.forEach(item => {
                        item.__radio = item.purchase_order_no === row.purchase_order_no;
                    });
                };

                // 查询进货单
                const queryPurchaseOrders = async () => {
                    try {
                        const res = await axios.get('/api/PurchaseOrder/GetRelatedOrders', {
                            params: {
                                inboundType: formData.inbound_type,
                                status: purchaseOrderSearchForm.status ? [purchaseOrderSearchForm.status] : ['5', '8'],
                                supplierId: purchaseOrderSearchForm.supplier,
                                purchaseOrderNo: purchaseOrderSearchForm.purchaseOrderNo,
                                purchaser: purchaseOrderSearchForm.purchaser,
                                department: purchaseOrderSearchForm.department,
                                date: purchaseOrderSearchForm.date ? purchaseOrderSearchForm.date.toISOString().split('T')[0] : '',
                                currentPage: purchaseOrderCurrentPage.value,
                                pageSize: purchaseOrderPageSize.value
                            }
                        });
                        purchaseOrderTableData.value = res.data.data;
                        purchaseOrderTotal.value = res.data.total;
                    } catch (err) {
                        ElementPlus.ElMessage.error('查询进货单失败');
                    }
                };
                
                const warehouseList = ref([]);

                //查询库位
                const storage = async () =>{
                    console.log(formData.warehouse_id);
                    const res = await axios.get('/api/PurchaseOrder/GetListStorage',{
                            params: { id: formData.warehouse_id }
                    })
                    console.log(res.data.data)
                    warehouseList.value = res.data.data;
                }
                const supp_id = ref('');
                // 确认选择进货单
                const confirmSelectPurchaseOrder = async () => {
                    const selectedRow = purchaseOrderTableData.value.find(item => item.__radio);
                    if (!selectedRow) {
                        ElementPlus.ElMessage.warning('请选择进货单');
                        return;
                    }
                    formData.related_order_no = selectedRow.purchase_order_no;
                    selectPurchaseOrderDialogVisible.value = false;

                    // 加载进货单明细
                    try {
                        const res = await axios.get('/api/PurchaseOrder/GetPurchaseOrderDetail', {
                            params: { orderNo: selectedRow.purchase_order_no }
                        });
                        console.log("详情：");
                        console.log(res.data.data)
                        const Main = res.data.data.main;
                        const Details = res.data.data.details;
                        console.log(Main);
                        // 回填供应商信息
                        formData.supplier_id = Main.supplierName;
                        supp_id.value = Main.suppliers_id;
                        formData.contact_person = Main.contact_person;
                        formData.contact_information = Main.contact_information;

                        // 转换明细数据
                        tableData.value = Details.map(detail => ({
                            purchase_order_no: formData.related_order_no,
                            product_name: detail.product_name,
                            product_code: detail.product_code,
                            specification_model: detail.specification_model,
                            type_of_goods: detail.type_of_goods,
                            type_of_goods_name: detail.type_of_goods_name,
                            unit: detail.unit,
                            unit_name: detail.unit_name,
                            current_inventory: detail.current_inventory, // 可从库存表关联，此处暂为0
                            prod_num: detail.prod_num,
                            stkIn_num: detail.stkIn_num,
                            uninbound_quantity: (detail.prod_num || 0) - (detail.stkIn_num || 0),
                            inbound_location: '',
                            this_inbound_quantity: 0,
                            purchase_unit_price: detail.purchase_unit_price,
                            batch_no: '',
                            production_date: '',
                            note: detail.note
                        }));
                    } catch (err) {
                        ElementPlus.ElMessage.error('加载明细失败');
                    }
                };
                
                // 货品选择相关
                const dialogVisible = ref(false);
                const goodsSearchForm = reactive({ goodsCodeName: '', unit: '' });
                const selectedGoods = ref([]);
                const goodsTableData = ref([]);
                const goodsCurrentPage = ref(1);
                const goodsPageSize = ref(10);
                const goodsTotal = ref(0);
                const unitOptions = ref([
                    { dictValue: '1', dictLabel: '吨' },
                    { dictValue: '2', dictLabel: '千克' },
                    { dictValue: '8', dictLabel: '个' }
                ]);

                // 打开货品选择框
                const openGoodsDialog = () => {
                    dialogVisible.value = true;
                    queryGoods(); // 打开时默认查询
                };

                // 查询货品
                const queryGoods = async () => {
                    try {
                        let url = '/api/Product/GetList';
                        if (isRelatePurchaseOrder.value) {
                            url = '/api/PurchaseOrder/GetOrderGoods';
                        }
                        const res = await axios.get(url, {
                            params: {
                                codeOrName: goodsSearchForm.goodsCodeName,
                                unit: goodsSearchForm.unit,
                                orderNo: isRelatePurchaseOrder.value ? formData.related_order_no : '',
                                page: goodsCurrentPage.value,
                                size: goodsPageSize.value
                            }
                        });
                        goodsTableData.value = res.data.data;
                        goodsTotal.value = res.data.total;
                    } catch (err) {
                        ElementPlus.ElMessage.error('查询货品失败');
                    }
                };

                // 确认选择货品
                const confirmSelectGoods = () => {
                    if (selectedGoods.value.length === 0) {
                        ElementPlus.ElMessage.warning('请选择货品');
                        return;
                    }
                    selectedGoods.value.forEach(item => {
                        const exists = tableData.value.some(row => row.product_code === item.product_code);
                        if (!exists) {
                            tableData.value.push(isRelatePurchaseOrder.value ? {
                                ...item,
                                inbound_location: '',
                                this_inbound_quantity: 0,
                                batch_no: '',
                                production_date: '',
                                note: ''
                            } : {
                                ...item,
                                current_inventory: item.current_inventory || 0,
                                inbound_location: '',
                                this_inbound_quantity: 0,
                                batch_no: '',
                                production_date: '',
                                note: ''
                            });
                        }
                    });
                    dialogVisible.value = false;
                    selectedGoods.value = [];
                };

                // 表格操作
                const handleSelectionChange = (val) => { selectedRows.value = val; };
                const handleDeleteRow = (row) => {
                    tableData.value = tableData.value.filter(item => item.product_code !== row.product_code);
                };
                const removeGoodsRow = () => {
                    if (selectedRows.value.length === 0) {
                        ElementPlus.ElMessage.warning('请选择要移除的行');
                        return;
                    }
                    const codes = selectedRows.value.map(r => r.product_code);
                    tableData.value = tableData.value.filter(item => !codes.includes(item.product_code));
                    multipleTableRef.value.clearSelection();
                };

                // 供应商变更
                const handleSupplierChange = (id) => {
                    const supplier = supplierOptions.value.find(s => s.supplier_id === id);
                    if (supplier) {
                        formData.contact_person = supplier.contact_person;
                        formData.contact_information = supplier.contact_information;
                    }
                };


            const saveForm = async (saveType) => {
                try {
                    // 1. 表单验证（原有逻辑保留）
                    if (!formData.inbound_type) return ElMessage.warning('请选择入库类型');
                    if (!formData.warehouse_id) return ElMessage.warning('请选择仓库');
                    if (!formData.inbound_date) return ElMessage.warning('请选择入库日期');
                    if (!formData.handler) return ElMessage.warning('请选择经办人');
                    if (tableData.value.length === 0) return ElMessage.warning('请添加入库明细');
                    
                    const invalidItem = tableData.value.find(item => !item.this_inbound_quantity || item.this_inbound_quantity <= 0 || !item.inbound_location);
                    if (invalidItem) return ElMessage.warning('入库明细的“本次入库数量”必须大于0且“入库库位”为必填');
                    if (isRelatePurchaseOrder.value) {
                        const overLimitItem = tableData.value.find(item => 
                            item.this_inbound_quantity > item.uninbound_quantity
                        );
                        if (overLimitItem) {
                            return ElMessage.error(`货品【${overLimitItem.product_name}】的入库数量超过未入库数量（${overLimitItem.uninbound_quantity}）`);
                        }
                    }
            
                    // 2. 构造请求体（严格对齐后端 InboundOrderRequest 字段）
                    const requestData = {
                        warehouse_receipt_no: formData.inbound_no,
                        warehouse_id: Number(formData.warehouse_id), // 转数字，匹配后端 int 类型
                        storage_status:'',
                        warehouse_name: WarehouseTableData.value.find(w => w.warehouse_id === formData.warehouse_id)?.warehouse_name || '',
                        rule_id: 2,
                        type_id: Number(formData.inbound_type), // 转数字，匹配后端 int 类型
                        storage_type: warehousingOptions.value.find(opt => opt.dictValue === formData.inbound_type)?.dictLabel || '',
                        date_of_storage: formData.inbound_date.toISOString().split('T')[0], // 格式：yyyy-MM-dd
                        associated_order_no: formData.related_order_no || '',
                        suppliers_id: supp_id.value ? Number(supp_id.value) : 0, // 转数字
                        handler_id: Number(formData.handler), // 转数字
                        organizations_id: 1, // 可根据业务调整
                        note: formData.note || '',
                        details: tableData.value.map(item => ({ // 明细字段严格对齐 InboundDetailRequest
                            product_code: item.product_code,
                            inbound_quantity: item.this_inbound_quantity,
                            inbound_location: item.inbound_location,
                            batch_no: item.batch_no || '',
                            production_date: item.production_date ? item.production_date.toISOString().split('T')[0] : '',
                            note: item.note || '',
                            unit_price:item.purchase_unit_price,
                        }))
                    };
            
                    console.log(requestData)
            
                    // 3. 调用后端接口（显式设置请求头，确保 JSON 格式）
                    const response = await axios.post('/api/InboundOrder/Add', requestData, {
                        headers: { 'Content-Type': 'application/json' }
                    });
            
                    // 4. 处理响应（原有逻辑保留）
                    if (response.data.success) {
                        ElementPlus.ElMessage.success(saveType === 'draft' ? '草稿保存成功' : '入库单保存成功');
                        setTimeout(() => {
                            window.location.href = '/StockIn/Index';
                        }, 1000);
                        if (saveType === 'saveAndAdd') 
                        {
                            formData.inbound_no = '';
                            formData.related_order_no = '';
                            tableData.value = [];
                            await generateLocationNumber();
                        }
                    } else {
                        ElMessage.error(`保存失败：${response.data.message}`);
                    }
                } catch (error) {
                    console.error('添加入库单异常:', error);
                    ElMessage.error('网络异常，无法完成添加操作');
                }
            };

            // 实时修正输入的入库数量（输入时触发）
            const handleInboundQuantityInput = (row) => {
                console.log("row2")
                console.log(row)
                if (isRelatePurchaseOrder.value) {
                    // 若输入为空，重置为0
                    if (row.this_inbound_quantity === undefined || row.this_inbound_quantity === null) {
                        row.this_inbound_quantity = 0;
                    }
                    // 若超过未入库数量，强制设为未入库数量
                    if (row.this_inbound_quantity > row.uninbound_quantity) {
                        row.this_inbound_quantity = row.uninbound_quantity;
                        ElMessage.warning(`本次入库数量不能超过未入库数量（${row.uninbound_quantity}）`);
                    }
                }
            };
            
            // 失去焦点时再次校验（防止粘贴超限值）
            const handleInboundQuantityChange = (row) => {
                console.log("row")
                console.log(row)
                if (isRelatePurchaseOrder.value && row.this_inbound_quantity > row.uninbound_quantity) {
                    row.this_inbound_quantity = row.uninbound_quantity;
                    ElMessage.warning(`已自动调整为最大可入库数量：${row.uninbound_quantity}`);
                }
            };

             
                // 页面操作
                const goBack = () => window.history.back();
                const saveDraft = async () => await saveForm('draft');
                const saveAndAdd = async () => {
                    await saveForm('save');
                    formData.inbound_no = '';
                    formData.related_order_no = '';
                    tableData.value = [];
                };
                const save = async () => await saveForm('save');

                // 附件上传点击处理（空方法，仅为保持事件绑定一致性）
                const handleUploadClick = () => {};

               

                // 附件上传
                const beforeUpload = (file) => {
                    const allowed = ['doc', 'docx', 'pdf', 'rar', 'zip'];
                    const ext = file.name.split('.').pop().toLowerCase();
                    if (!allowed.includes(ext)) {
                        ElementPlus.ElMessage.error('仅支持 doc、docx、pdf、rar、zip 格式');
                        return false;
                    }
                    if (file.size > 200 * 1024 * 1024) {
                        ElementPlus.ElMessage.error('文件大小不能超过200MB');
                        return false;
                    }
                    return true;
                };
                const handleUploadSuccess = (response) => {
                    if (response.success) ElementPlus.ElMessage.success('上传成功');
                    else ElementPlus.ElMessage.error('上传失败');
                };

                // 分页及重置方法
                const resetGoodsForm = () => { goodsSearchForm.goodsCodeName = ''; goodsSearchForm.unit = ''; };
                const handleGoodsPageSizeChange = (size) => { goodsPageSize.value = size; queryGoods(); };
                const handleGoodsCurrentPageChange = (page) => { goodsCurrentPage.value = page; queryGoods(); };
                const resetPurchaseOrderForm = () => { Object.keys(purchaseOrderSearchForm).forEach(k => purchaseOrderSearchForm[k] = ''); };
                const handlePurchaseOrderPageSizeChange = (size) => { purchaseOrderPageSize.value = size; queryPurchaseOrders(); };
                const handlePurchaseOrderCurrentPageChange = (page) => { purchaseOrderCurrentPage.value = page; queryPurchaseOrders(); };

                return {
                    formData, isRelatePurchaseOrder, fileList, tableData, multipleTableRef, selectedRows,
                    calculateTotalNum, calculateTotalAmount, warehousingOptions, WarehouseData, supplierOptions,
                    selectPurchaseOrderDialogVisible, purchaseOrderSearchForm, purchaseOrderTableData,
                    purchaseOrderCurrentPage, purchaseOrderPageSize, purchaseOrderTotal, dialogVisible,
                    goodsSearchForm, selectedGoods, goodsTableData, goodsCurrentPage, goodsPageSize, goodsTotal,
                    unitOptions, handleInboundTypeChange, handleRelatedOrderInputClick, handleRelatePurchaseOrderChange,
                    handlePurchaseOrderRowClick, queryPurchaseOrders, confirmSelectPurchaseOrder, openGoodsDialog,
                    queryGoods, confirmSelectGoods, handleSelectionChange, handleDeleteRow, removeGoodsRow,
                    handleSupplierChange, goBack, saveDraft, saveAndAdd, save, beforeUpload, handleUploadSuccess,
                    handleUploadClick, resetGoodsForm, handleGoodsPageSizeChange, handleGoodsCurrentPageChange, resetPurchaseOrderForm,
                    handlePurchaseOrderPageSizeChange, handlePurchaseOrderCurrentPageChange,WarehouseTableData,handleWarehouseChange,
                    warehouseList,handleInboundQuantityInput,handleInboundQuantityChange
                };
            }
        });
        app.use(ElementPlus);
        app.mount('.container');
    </script>
</body>
</html>